#include <QDebug>
#include <QFileInfo>
#include <gumbo.h>

#include "imagepageparser.h"
#include "imagedownloader.h"
#include "constants.h"
#include "utils.h"

namespace Jcr
{
class ImagePageParserPrivate
{
public:
    QStringList imageLinks;
    std::list<std::string> imgUrls;
    int savedFileCount = 0;
    int savedFileCounter = 0;
    void traverseNode(GumboNode* node);
    void getImageLinks(GumboNode* node);
};

void ImagePageParserPrivate::traverseNode(GumboNode *node)
{
    if (node->type != GUMBO_NODE_ELEMENT)
        return;

    GumboAttribute* attr = nullptr;
    if (node->v.element.tag == GUMBO_TAG_A &&
        (attr = gumbo_get_attribute(&node->v.element.attributes, "class")) &&
        ((strcasecmp(attr->value, "normalthumb") == 0) ||
         (strcasecmp(attr->value, "currthumb") == 0))) {
        GumboVector* children = &node->v.element.children;
        for (unsigned int i = 0; i < children->length; ++i) {
            GumboNode* subNode = static_cast<GumboNode*>(children->data[i]);
            GumboAttribute* subAttr = gumbo_get_attribute(&subNode->v.element.attributes, "src");
            imageLinks.push_back(subAttr->value);
        }
    }

    GumboVector* children = &node->v.element.children;
    for (unsigned int i = 0; i < children->length; ++i)
        traverseNode(static_cast<GumboNode*>(children->data[i]));
}

ImagePageParser::ImagePageParser(QObject* parent) : ModelPageParser(parent)
{
    d_ptr = new ImagePageParserPrivate;
//    setUrl(QUrl(Jcr::TESTMODELIMAGEPAGE));
}

ImagePageParser::~ImagePageParser()
{
    delete d_ptr;
}

const QStringList& ImagePageParser::images() const
{
    return d_ptr->imageLinks;
}

void ImagePageParser::processNode(GumboNode *node)
{
    GumboAttribute* attr = nullptr;
    if (node->v.element.tag == GUMBO_TAG_A &&
       (attr = gumbo_get_attribute(&node->v.element.attributes, "class")) &&
       ((strncasecmp(attr->value, "normalthumb") == 0) || (strncasecmp(attr->value, "currthumb") == 0))) {
        GumboVector* children = &node->v.element.children;
        for (unsigned int i = 0; i < children->length; ++i) {
            GumboNode* subNode = static_cast<GumboNode*>(children->data[i]);
            GumboAttribute* subAttr = gumbo_get_attribute(&subNode->v.element.attributes, "src");
            d_ptr->imageLinks.push_back(subAttr->value);

        }
    }
}

void ImagePageParser::finalize()
{
    // now download each image to the dir: brand/model/
    // because the saved image links are all smaller version of images
    // we should save two versions of images ?
    // one small and one big ?
    qDebug() << d_ptr->imageLinks;
    d_ptr->savedFileCounter = 0;
    d_ptr->savedFileCount = d_ptr->imageLinks.size() * 2; // both samll & big versions
#if 1
    QString brand = this->brandName().isEmpty() ? "Other" : this->brandName();
    QString validModelName = this->modelName();
    validModelName.replace("/", "-"); // in case there're any invalid characters in the path.
    QString saveDir = Jcr::Utils::makeDirectory(brand, validModelName);
    foreach (auto image, d_ptr->imageLinks) {
        QUrl imageUrl(image);

        ImageDownloader* id = new ImageDownloader(imageUrl, saveDir, nullptr);
        connect(id, SIGNAL(finished()), this, SLOT(onFinishedDownloadingImage()));
        id->run();

        ImageDownloader* idBig = new ImageDownloader(Jcr::Utils::bigImageLink(imageUrl), saveDir, nullptr);
        connect(idBig, SIGNAL(finished()), this, SLOT(onFinishedDownloadingImage()));
        idBig->run();
    }
#endif
    emit finished();
}

void ImagePageParser::onFinishedDownloadingImage()
{
    qDebug() << "!!!!!!!!!!!!!" << __FUNCTION__;
    ImageDownloader* id = qobject_cast<ImageDownloader*>(sender());
    id->deleteLater();

    if (++d_ptr->savedFileCounter >= d_ptr->savedFileCount)
        emit finishedSavingImages();
}

// http://img.newmotor.com.cn/UploadFiles/2015-06/234/2015061618030020446_S.jpg
} // namespace jcr
